<template>
<div class="image-uploader">
  <el-upload
    action="/api/upload"
    :headers="{ Authorization: `Bearer ${token}` }"
    :show-file-list="false"
    :disabled="disabled"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
  >
    <div class="upload-wrapper" :style="{ aspectRatio }">
      <img v-if="modelValue" :src="modelValue" class="preview-image" />
      <el-icon v-else class="upload-icon"><Plus /></el-icon>

      <div v-if="!disabled" class="upload-mask">
        <span>{{ modelValue ? '点击更换' : '点击上传' }}</span>
      </div>
    </div>
  </el-upload>
</div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: String,
  disabled: Boolean,
  aspectRatio: {
    type: String,
    default: '1:1'
  }
})

const emit = defineEmits(['update:modelValue'])
const token = computed(() => localStorage.getItem('token'))

const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG 格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

const handleSuccess = (res: any) => {
  if (res.code === 200) {
    emit('update:modelValue', res.data)
    ElMessage.success('上传成功')
  }
}
</script>

<style scoped lang="scss">
.image-uploader {
  .upload-wrapper {
    position: relative;
    border: 2px dashed var(--el-border-color);
    border-radius: 8px;
    overflow: hidden;
    background: #f8f9fa;
    transition: border-color 0.3s;

    &:hover {
      border-color: var(--el-color-primary);
    }

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .upload-icon {
      font-size: 28px;
      color: #8c939d;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .upload-mask {
      position: absolute;
      inset: 0;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;

      &:hover {
        opacity: 1;
      }
    }
  }
}
</style>
